import { Point } from "ol/geom";
import { Feature } from "ol";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import { Icon, Style, Text, Fill, Stroke } from "ol/style";
import XYZ from "ol/source/XYZ";
import TileLayer from "ol/layer/Tile";
// 天地图密钥
var key = "2b652d4e7858f5a1310620992c2cfe3c"; // 你的API Key
var siteindex = Math.round(Math.random() * 7); // 天地图的多个节点选择
// 导入城市数据
import { cities } from "@/views/layer-management/common/data.js";
// 创建一个空的矢量图层
const vectorSource = new VectorSource();

// 动态生成城市标注
cities.forEach((city) => {
  const point = new Point(city.coords);
  const feature = new Feature({
    geometry: point,
    name: city.name, // 存储城市名称
  });

  // 为每个标注设置样式（可自定义图标）
  const iconStyle = new Style({
    image: new Icon({
      src: "https://openlayers.org/en/v6.9.0/examples/data/icon.png", // 图标路径
      scale: 0.5, // 图标缩放
      anchor: [0.5, 1], // 图标锚点，设置在底部中央
    }),
    text: new Text({
      text: city.name, // 使用城市名称作为标注文本
      font: "12px Arial", // 设置字体
      fill: new Fill({ color: "#000" }), // 设置文字颜色
      stroke: new Stroke({ color: "#fff", width: 3 }), // 文字描边
      offsetY: 10, // 向上偏移，使文字不被图标遮挡
    }),
  });
  feature.setStyle(iconStyle);

  // 将标注添加到矢量图层
  vectorSource.addFeature(feature);
});

// 创建矢量图层
export const vectorLayer = new VectorLayer({
  source: vectorSource,
  zIndex: 10, // 确保点标注图层在其他图层之上
});

// 天地图影像底图图层 （卫星图层）
export const img_wLayer = new TileLayer({
  source: new XYZ({
    url: "https://t" + siteindex + ".tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + key,
    crossOrigin: "Anonymous",
    cacheSize: 2048, // 提高缓存容量
    tileSize: 512, // 调整瓦片大小（增加瓦片尺寸，减少请求次数）
    tileLoadFunction: (imageTile, src) => {
      const image = new Image();
      image.onload = () => {
        imageTile.getImage().src = image.src;
      };
      // 支持 WebP 格式
      image.src = src.replace(/\.png$/, ".webp");
    },
  }),
  title: "影像底图",
  maxZoom: 18,
  zIndex: 1,
});
